/*
 * 文件名：ParkwellPayBillServiceImpl.java	 
 * 时     间：上午10:42:45
 * 作     者：Administrator       
 * 版     权： 2012-2022 湖南智软网络科技, 公司保留所有权利.
 * 联     系：http://www.073586.com/
 */
package com.local.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloud.threads.UpLoadCarOutInfoRunble;
import com.cloud.threads.UploadCouponRunble;
import com.cloud.threads.UploadPayBillRunble;
import com.cz073586.tools.util.DateUtil;
import com.cz073586.tools.util.ThreadPoolUtil;
import com.local.common.CommonContains;
import com.local.common.PayTypeConstans;
import com.local.dao.hismappers.LocalPayBillMapper;
import com.local.dao.mapers.CarParkInMapper;
import com.local.dao.mapers.CarParkOutMapper;
import com.local.dao.mapers.LocalCarTypeMapper;
import com.local.dao.mapers.LocalEquipmentMapper;
import com.local.dao.mapers.LocalPayBillCopyMapper;
import com.local.dao.mapers.LocalPayBillRepeatMapper;
import com.local.dao.mapers.LocalStationMapper;
import com.local.entity.ex.LocalPayBillEx;
import com.local.entity.vo.ParkwellPayBillVo;
import com.local.entity.vo.WorkUserPayBillVo;
import com.local.manager.cfgManager.CloudConfigManager;
import com.local.model.AdminCarInBill;
import com.local.model.CarParkIn;
import com.local.model.CarParkOut;
import com.local.model.Crossing;
import com.local.model.Integration;
import com.local.model.LocalCarType;
import com.local.model.LocalCoupon;
import com.local.model.LocalEquipment;
import com.local.model.LocalEquipmentExample;
import com.local.model.LocalPayBill;
import com.local.model.LocalPayBillCopy;
import com.local.model.LocalPayBillExample;
import com.local.model.LocalPayBillRepeat;
import com.local.model.LocalPayBillRepeatExample;
import com.local.model.LocalStation;
import com.local.model.LocalStationExample;
import com.local.page.ParkwellPayBillPage;
import com.local.service.face.AdminCarInBillService;
import com.local.service.face.CarInAndOutService;
import com.local.service.face.CrossingService;
import com.local.service.face.IntegrationService;
import com.local.service.face.LocalCouponService;
import com.local.service.face.LocalVersionService;
import com.local.service.face.LogService;
import com.local.service.face.ParkwellPayBillService;
import com.local.util.MyDateUtil;
import com.qianhai.common.dao.face.BaseMapper;
import com.qianhai.common.exception.BaseException;
import com.qianhai.common.service.impl.BaseServiceImpl;
import com.qianhai.common.utils.BeanUtil;
import com.qianhai.common.utils.ShiroUtil;
import com.qianhai.common.utils.Tools;
import com.qianhai.common.utils.UUIDGenerateUtil;
import common.cz0735.coustomer.mapers.CoustomerInfoMapper;
import common.cz0735.coustomer.model.CoustomerInfo;
import common.cz0735.coustomer.model.CoustomerInfoExample;

/**
 * 类描述:停车场支付流水
 * 
 * @ClassName: ParkwellPayBillServiceImpl
 * @author Administrator
 * @date 2015年4月7日 上午10:42:45
 */
@Service
public class ParkwellPayBillServiceImpl extends
		BaseServiceImpl<LocalPayBillExample, LocalPayBill, String> implements
		ParkwellPayBillService
{
	@Autowired
	private LocalPayBillMapper localPayBillMapper;
	
	@Autowired
	private LocalPayBillCopyMapper localPayBillCopyMapper;
	
	@Autowired
	private LocalPayBillRepeatMapper localPayBillRepeatMapper;
	
	@Autowired
	private LocalCouponService localCouponService;
	
	@Autowired
	private CarParkOutMapper carParkOutMapper;
	
	@Autowired
	private LocalVersionService localVersionService;
	
	@Autowired
	private LocalEquipmentMapper localEquipmentMapper;
	
	@Autowired
	private CarInAndOutService carInAndOutService;
	
	@Autowired
	private CarParkInMapper carParkInMapper;
	
	@Autowired
	private CrossingService crossinServer;
	
	@Autowired
	private AdminCarInBillService adminCarInBillService;
	
	@Autowired
	private LocalCarTypeMapper localCarTypeMapper;
	
	@Autowired
	private IntegrationService integrationService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private CoustomerInfoMapper custMapper;
	
	@Autowired
	private LocalStationMapper localStationMapper;
	
	@Override
	public String saveParkwellPayBill(LocalPayBill parkwellPayBill)
	{
		try
		{
			
			// 判断重复插入
			if (!Tools.isEmpty(parkwellPayBill.getPayBillUuid()))
			{
				LocalPayBill bill = localPayBillMapper
						.selectByPrimaryKey(parkwellPayBill.getPayBillUuid());
				if (!Tools.isEmpty(bill))
				{
					parkwellPayBill.getPayBillUuid();
				}
			}
			parkwellPayBill.setPayBillUuid(UUIDGenerateUtil.generate());
			parkwellPayBill.setPayTime(new Date(System.currentTimeMillis()));
			parkwellPayBill
					.setVersion(localVersionService
							.selectLocalVersionByVersionType(CommonContains.VERSION_PAY_BILL));
			localPayBillMapper.insertSelective(parkwellPayBill);
			if (CloudConfigManager.instance().isOpen())
			{
				UploadPayBillRunble upload = new UploadPayBillRunble(
						parkwellPayBill, logService);
				ThreadPoolUtil.instance().execute(upload);
			}
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
		return parkwellPayBill.getPayBillUuid();
	}
	
	@Override
	public List<LocalPayBill> findAllParkwellPayBillByQueryForm(
			ParkwellPayBillPage<LocalPayBill> pageInfo)
	{
		Integer recordCount = localPayBillMapper.countAllByPage(pageInfo);
		pageInfo.setTotalRecords(recordCount);
		List<LocalPayBill> list = localPayBillMapper.queryByPage(pageInfo);
		
		// 处理客户名称后的返回结果列表
		List<LocalPayBill> listResut = new ArrayList<LocalPayBill>();
		// 查询的结果中只有值班人员的uuid，需一次通过uuid查询出cusName信息
		List<String> cusIdList = new ArrayList<String>();
		// 查询的结果中只有岗亭的uuid，需一次通过uuid查询出岗亭名称
		List<String> stationIdList = new ArrayList<String>();
		if (!Tools.isEmpty(list) && !list.isEmpty())
		{
			for (LocalPayBill billInfo : list)
			{
				// 操作人
				if (!Tools.isEmpty(billInfo.getUserId()))
				{
					cusIdList.add(billInfo.getUserId());
				}
				
				// 操作人
				if (!Tools.isEmpty(billInfo.getAttr3())) // 使用预留字段attr3作为岗亭的uuid
				{
					stationIdList.add(billInfo.getAttr3());
				}
				
			}
		}
		
		Map<String, String> cusIdAndCusName = new HashMap<String, String>();
		if (!Tools.isEmpty(cusIdList) && !cusIdList.isEmpty())
		{
			log.debug("the billinfolist cusId list is : '" + cusIdList + "'.");
			// 根据cusIdList 一次查询出cusName信息
			CoustomerInfoExample custEx = new CoustomerInfoExample();
			custEx.or().andLoginUserUuidIn(cusIdList);
			List<CoustomerInfo> custList = custMapper.selectByCondition(custEx);
			
			if (!Tools.isEmpty(custList) && !custList.isEmpty())
			{
				for (CoustomerInfo customerInfo : custList)
				{
					cusIdAndCusName.put(customerInfo.getLoginUserUuid(),
							customerInfo.getName());
				}
			}
		}
		
		Map<String, String> stationIdAndName = new HashMap<String, String>();
		if (!Tools.isEmpty(stationIdList) && !stationIdList.isEmpty())
		{
			log.debug("the billinfolist stationIdList list is : '"
					+ stationIdList + "'.");
			// 根据stationIdList 一次查询出岗亭名称信息
			
			LocalStationExample stationEx = new LocalStationExample();
			stationEx.or().andStationUuidIn(stationIdList);
			List<LocalStation> stationList = localStationMapper
					.selectByCondition(stationEx);
			
			if (!Tools.isEmpty(stationList) && !stationList.isEmpty())
			{
				for (LocalStation stationInfo : stationList)
				{
					stationIdAndName.put(stationInfo.getStationUuid(),
							stationInfo.getStationName());
				}
			}
		}
		
		if (!Tools.isEmpty(list) && !list.isEmpty())
		{
			for (LocalPayBill billInfo : list)
			{
				LocalPayBillEx exInfo = new LocalPayBillEx();
				BeanUtil.copyProperties(exInfo, billInfo);
				String cusName = cusIdAndCusName.get(billInfo.getUserId());
				exInfo.setCustName(cusName);
				
				String stationName = stationIdAndName.get(billInfo.getAttr3());
				exInfo.setStationName(stationName);
				
				listResut.add(exInfo);
			}
		}
		
		// //////////////
		// for (LocalPayBill billInfo : list)
		// {
		// LocalPayBillEx exInfo = new LocalPayBillEx();
		// BeanUtil.copyProperties(exInfo, billInfo);
		//
		// // 操作人
		// if (!Tools.isEmpty(billInfo.getUserId()))
		// {
		// CoustomerInfoExample custEx = new CoustomerInfoExample();
		// custEx.or().andLoginUserUuidEqualTo(billInfo.getUserId());
		// List<CoustomerInfo> custList = custMapper
		// .selectByCondition(custEx);
		//
		// if (!Tools.isEmpty(custList) && !custList.isEmpty())
		// {
		// exInfo.setCustName(custList.get(0).getName());
		// }
		// }
		//
		// listResut.add(exInfo);
		//
		// }// end for
		// // //////////////////////
		
		pageInfo.setData(listResut);
		return listResut;
	}
	
	@SuppressWarnings("unused")
	private LocalEquipment queryEquipmentByStationId(String stetionId)
	{
		LocalEquipmentExample ex = new LocalEquipmentExample();
		ex.or().andStationUuidEqualTo(stetionId.trim());
		List<LocalEquipment> list = localEquipmentMapper.selectByCondition(ex);
		return list.isEmpty() ? null : list.get(0);
	}
	
	@Override
	public void saveParkwellPayBill(LocalPayBill localPayBill,
			String carOutUuid, String stationUuid, String crossinId,
			ParkwellPayBillVo parkwellPayBillVo)
	{
		try
		{
			this.saveParkwellPayBill(localPayBill);
			
			// 能检车到相机传送过来的车辆出场信息
			if (!Tools.isEmpty(carOutUuid))
			{
				// throw new BaseException("50000-00001-00041");
				CarParkOut carParkOut = carParkOutMapper
						.selectByPrimaryKey(carOutUuid);
				if (!Tools.isEmpty(carParkOut))
				{
					carParkOut.setCarInUuid(localPayBill.getParkInUuid());
					carParkOut.setStatus(0);
					
					carParkOutMapper.updateByPrimaryKey(carParkOut);
					
					// 如果有进场状态为0,推送到平台更新进场纪录状态
					if (!Tools.isEmpty(carParkOut.getCarInUuid()))
					{
						CarParkIn carInInfo = carParkInMapper
								.selectByPrimaryKey(carParkOut.getCarInUuid());
						if (!Tools.isEmpty(carInInfo))
						{
							carInInfo.setStatus(0);
							carParkInMapper
									.updateByPrimaryKeySelective(carInInfo);
						}
					}
					
					// if (CloudConfigManager.instance().isOpen())
					// {
					// UpDateCarOutInfoRunble upload = new
					// UpDateCarOutInfoRunble(
					// carParkOut,logService);
					// ThreadPoolUtil.instance().execute(upload);
					// }
				}
			}
			
			// 车辆出场时，没有检测到相机传送上来的出场信息
			if (Tools.isEmpty(carOutUuid))
			{
				CarParkOut carOutInfo = new CarParkOut();
				Date date = new Date();
				carOutInfo.setUuid(UUIDGenerateUtil.generate());
				carOutInfo.setCreateTime(date);
				carOutInfo.setCarNo(parkwellPayBillVo.getCarNo());
				carOutInfo.setExchangeUuid(parkwellPayBillVo.getExchangeUuid());
				carOutInfo.setEquipment(parkwellPayBillVo.getEquimentNo());
				carOutInfo.setOpenTime(DateUtil.getNowTimestampStr());
				carOutInfo.setStatus(0);
				carOutInfo.setCarInUuid(parkwellPayBillVo.getCarInUuid());
				carParkOutMapper.insertSelective(carOutInfo);
				
				if (CloudConfigManager.instance().isOpen())
				{
					UpLoadCarOutInfoRunble upload = new UpLoadCarOutInfoRunble(
							carOutInfo, logService);
					ThreadPoolUtil.instance().execute(upload);
				}
			}
			
			// 执行开闸指令
			crossinServer.openGATE(crossinId, stationUuid);
			// MiddlewareManager.instance().sendInstruct(localEquipment.getCameraNo(),
			// "1", "192.168.1.100");
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
	}
	
	@Override
	public CarParkIn selectCarNo(String carNo)
	{
		// TODO Auto-generated method stub
		return carParkInMapper.selectCarNo(carNo);
	}
	
	public Double queryPayBillByCondition(LocalPayBill localPayBill)
	{
		
		return localPayBillMapper.selectSumPrice(localPayBill);
		
	}
	
	@Override
	public Integer savePayBill(ParkwellPayBillVo parkwellPayBillVo)
			throws BaseException
	{
		try
		{
			if (Tools.isEmpty(parkwellPayBillVo.getCarNo()))
			{
				throw new BaseException("50000-00001-00039");
			}
			
			String nowTime = DateUtil.getNowTimestampStr();
			
			if (Tools.isEmpty(parkwellPayBillVo.getCrossingId()))
			{
				throw new BaseException("50000-00001-00035");
			}
			
			List<LocalEquipment> listEquimnetList = crossinServer
					.queryEquimentByCrossionId(parkwellPayBillVo
							.getCrossingId());
			
			if (listEquimnetList.isEmpty())
			{
				throw new BaseException("50000-00001-00036");
			}
			
			// 获取设备信息列表，必须保证传输路口为一个设备
			LocalEquipment equiment = listEquimnetList.get(0);
			
			parkwellPayBillVo.setEquimentNo(equiment.getCameraNo());
			// 路口信息
			Crossing crossing = crossinServer.getCrossinByid(parkwellPayBillVo
					.getCrossingId());
			// 判断是进场信息还是出场信息
			if (crossing.getStatus() == 1)
			{
				if (Tools.isEmpty(parkwellPayBillVo.getCarInTimeString()))
				{
					parkwellPayBillVo.setCarInTimeString(nowTime);
				}
				// 入口
				parkwellPayBillVo.setExchangeUuid(equiment.getExchangeNo());
				addCarInBill(parkwellPayBillVo);
				return 1;
			}
			
			if (Tools.isEmpty(parkwellPayBillVo.getCarOutTimeString()))
			{
				parkwellPayBillVo.setCarOutTimeString(nowTime);
			}
			
			if (Tools.isEmpty(parkwellPayBillVo.getCarInTimeString()))
			{
				throw new BaseException("50000-00001-00040");
			}
			
			if (Tools.isEmpty(parkwellPayBillVo.getParkTimeString()))
			{
				throw new BaseException("50000-00001-00043");
			}
			
			// 判断金额
			if (Tools.isEmpty(parkwellPayBillVo.getTheoryPrice()))
			{
				throw new BaseException("50000-00001-00042");
			}
			
			CarParkIn carParkIn = selectCarNo(parkwellPayBillVo.getCarNo());
			LocalPayBill localPayBill = new LocalPayBill();
			localPayBill.setCarNo(parkwellPayBillVo.getCarNo());
			if (Tools.isEmpty(parkwellPayBillVo.getActualPrice()))
			{
				if (!Tools.isEmpty(parkwellPayBillVo.getCoupon()))
				{
					Integer dd = parkwellPayBillVo.getTheoryPrice()
							- parkwellPayBillVo.getCoupon();
					if (dd < 0)
					{
						dd = 0;
					}
					localPayBill.setActualPrice(dd.doubleValue());
				} else
				{
					localPayBill.setActualPrice(parkwellPayBillVo
							.getTheoryPrice().doubleValue());
				}
			}
			localPayBill.setParkInUuid(parkwellPayBillVo.getCarInUuid());
			localPayBill.setPrice(parkwellPayBillVo.getTheoryPrice()
					.doubleValue());
			localPayBill.setUserId(ShiroUtil.getCurrentUser().getUuid());
			localPayBill.setUserName(ShiroUtil.getCurrentUser().getLoginName());
			if (!Tools.isEmpty(carParkIn))
			{
				localPayBill.setParkInUuid(carParkIn.getUuid());
			}
			localPayBill.setPayType(Tools.isEmpty(parkwellPayBillVo
					.getPayType()) ? PayTypeConstans.MONEY_TYPE
					: parkwellPayBillVo.getPayType());
			saveParkwellPayBill(localPayBill, parkwellPayBillVo.getUuid(),
					parkwellPayBillVo.getStationUuid(),
					parkwellPayBillVo.getCrossingId(), parkwellPayBillVo);
			
			// 记录优惠卷流水
			if (!Tools.isEmpty(parkwellPayBillVo.getCoupon())
					&& parkwellPayBillVo.getCoupon() > 0)
			{
				LocalCoupon lcoupon = new LocalCoupon();
				lcoupon.setBillUuid(localPayBill.getPayBillUuid());
				lcoupon.setCarNo(parkwellPayBillVo.getCarNo());
				lcoupon.setCouponPrice(parkwellPayBillVo.getCoupon()
						.doubleValue());
				lcoupon.setCouponUuid(UUIDGenerateUtil.generate());
				lcoupon.setPayTime(new Date(System.currentTimeMillis()));
				lcoupon.setUserId(ShiroUtil.getCurrentUser().getUuid());
				lcoupon.setUserName(ShiroUtil.getCurrentUser().getLoginName());
				localCouponService.insert(lcoupon);
				
				if (CloudConfigManager.instance().isOpen())
				{
					UploadCouponRunble upload = new UploadCouponRunble(lcoupon,
							logService);
					ThreadPoolUtil.instance().execute(upload);
				}
			}
			
		} catch (Throwable t)
		{
			throw new BaseException(t.getMessage());
		}
		return null;
	}
	
	@Override
	public Integer addCarInBill(ParkwellPayBillVo parkwellPayBillVo)
			throws BaseException
	{
		try
		{
			
			// 如果该车牌有进场纪录,却又没出场纪录则重复添加.
			
			// 纪录流水
			CarParkIn carParkIn = new CarParkIn();
			carParkIn.setCarNo(parkwellPayBillVo.getCarNo());
			carParkIn.setExchangeUuid(parkwellPayBillVo.getExchangeUuid());
			carParkIn
					.setCarInTimeString(parkwellPayBillVo.getCarInTimeString());
			carParkIn.setEquipment(parkwellPayBillVo.getEquimentNo());
			carParkIn.setOpenTime(DateUtil.getNowTimestampStr());
			// 添加进场流水
			carInAndOutService.addCarParkInBill(carParkIn);
			
			AdminCarInBill adminCarInBill = new AdminCarInBill();
			adminCarInBill.setUuid(UUIDGenerateUtil.generate());
			adminCarInBill.setCarNo(parkwellPayBillVo.getCarNo());
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			adminCarInBill.setInTime(sd.parse(parkwellPayBillVo
					.getCarInTimeString()));
			adminCarInBill.setCrossingId(parkwellPayBillVo.getCrossingId());
			adminCarInBill.setExchangeNo(parkwellPayBillVo.getExchangeUuid());
			adminCarInBill.setLonginUserUuid(ShiroUtil.getCurrentUser()
					.getUuid());
			adminCarInBill.setStationUuid(parkwellPayBillVo.getStationUuid());
			adminCarInBillService.addAdminCarInBill(adminCarInBill);
		} catch (Throwable t)
		{
			throw new BaseException(t.getMessage());
		}
		return null;
	}
	
	@Override
	public LocalCarType queryCarType(LocalCarType carType)
	{
		// TODO Auto-generated method stub
		return localCarTypeMapper.queryCarType(carType);
	}
	
	@Override
	public List<LocalPayBill> queryPayBillByCarNo(String carNo)
	{
		try
		{
			// 最后一次进场，并且未出去过
			CarParkIn carInInfo = carParkInMapper.selectCarNo(carNo);
			if (!Tools.isEmpty(carInInfo))
			{
				List<LocalPayBill> listbillList = localPayBillMapper
						.queryAllBill(carInInfo.getUuid());
				return listbillList;
			}
		} catch (Exception e)
		{
			// TODO: handle exception
			return null;
		}
		return null;
	}
	
	@Override
	public List<LocalPayBill> queryHomeMobile()
	{
		// TODO Auto-generated method stub
		return localPayBillMapper.queryHomeMobile();
	}
	
	@Override
	public List<LocalPayBill> queryMoney(String userid)
	{
		// TODO Auto-generated method stub
		return localPayBillMapper.queryMoney(userid);
	}
	
	@Override
	public List<LocalPayBill> queryAuto()
	{
		// TODO Auto-generated method stub
		return localPayBillMapper.queryAuto();
	}
	
	@Override
	public List<LocalPayBill> queryMember()
	{
		// TODO Auto-generated method stub
		return localPayBillMapper.queryMember();
	}
	
	@Override
	public LocalPayBill queryLastBill(String carInUuid)
	{
		// TODO Auto-generated method stub
		LocalPayBill lp = localPayBillMapper.queryLastBill(carInUuid);
		return !Tools.isEmpty(lp) ? lp : null;
	}
	
	@Override
	public BaseMapper<LocalPayBillExample, LocalPayBill, String> getMapper()
	{
		// TODO Auto-generated method stub
		return localPayBillMapper;
	}
	
	@Override
	public LocalPayBill addOtherPayBill(LocalPayBill parkwellPayBill)
	{
		// TODO Auto-generated method stub
		try
		{
			// 判断重复插入
			if (!Tools.isEmpty(parkwellPayBill.getPayBillUuid()))
			{
				LocalPayBill bill = localPayBillMapper
						.selectByPrimaryKey(parkwellPayBill.getPayBillUuid());
				if (!Tools.isEmpty(bill))
				{
					parkwellPayBill.getPayBillUuid();
				}
			}
			parkwellPayBill.setPayBillUuid(UUIDGenerateUtil.generate());
			parkwellPayBill.setPayTime(!Tools.isEmpty(parkwellPayBill
					.getPayTime()) ? parkwellPayBill.getPayTime() : new Date(
					System.currentTimeMillis()));
			parkwellPayBill
					.setCarNo(!Tools.isEmpty(parkwellPayBill.getCarNo()) ? parkwellPayBill
							.getCarNo() : "无");
			parkwellPayBill.setPayType(!Tools.isEmpty(parkwellPayBill
					.getPayType()) ? parkwellPayBill.getPayType() : "现金");
			parkwellPayBill
					.setPrice(!Tools.isEmpty(parkwellPayBill.getPrice()) ? parkwellPayBill
							.getPrice() : 0d);
			
			// 通过车牌号找到最新的进场记录，ID
			CarParkIn cc = carParkInMapper.queryMaxInByCarNo(parkwellPayBill
					.getCarNo());
			parkwellPayBill.setParkInUuid(!Tools.isEmpty(cc) ? cc.getUuid()
					: null);
			parkwellPayBill
					.setActualPrice(!Tools.isEmpty(parkwellPayBill
							.getActualPrice()) ? parkwellPayBill
							.getActualPrice() : !Tools.isEmpty(parkwellPayBill
							.getPrice()) ? parkwellPayBill.getPrice() : 0d);
			parkwellPayBill.setCarinCreatAt(!Tools.isEmpty(parkwellPayBill
					.getCarinCreatAt()) ? parkwellPayBill.getCarinCreatAt()
					: cc.getCreateTime());
			parkwellPayBill.setCaroutCareteAt(!Tools.isEmpty(parkwellPayBill
					.getCaroutCareteAt()) ? parkwellPayBill.getCaroutCareteAt()
					: new Date());
			
			localPayBillMapper.insertSelective(parkwellPayBill);
			
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
		return parkwellPayBill;
	}
	
	@Override
	public LocalPayBill addOtherPayBill(ParkwellPayBillVo parkwellPayBillVo)
	{
		// TODO Auto-generated method stub
		LocalPayBill parkwellPayBill = new LocalPayBill();
		try
		{
			parkwellPayBill.setParkInUuid(!Tools.isEmpty(parkwellPayBillVo
					.getCarInUuid()) ? parkwellPayBillVo.getCarInUuid() : null);
			parkwellPayBill.setPayBillUuid(UUIDGenerateUtil.generate());
			parkwellPayBill.setCarNo(!Tools.isEmpty(parkwellPayBillVo
					.getCarNo()) ? parkwellPayBillVo.getCarNo() : null);
			parkwellPayBill.setPayTime(new Date(System.currentTimeMillis()));
			
			parkwellPayBill.setPrice(!Tools.isEmpty(parkwellPayBillVo
					.getTheoryPriceDb()) ? parkwellPayBillVo.getTheoryPriceDb()
					: 0);
			
			if (parkwellPayBillVo.getCarNoTye().equals(
					PayTypeConstans.MENMBER_TYPE)
					|| parkwellPayBillVo.getCarNoTye().equals("白名单"))
			{
				parkwellPayBill.setActualPrice(0d);
			} else
			{
				
				parkwellPayBill.setActualPrice(!Tools.isEmpty(parkwellPayBillVo
						.getPriceDifference()) ? parkwellPayBillVo
						.getPriceDifference() : 0);
			}
			
			// 如果没有指定支付类型则为自动开闸出场车辆,否则为收现金执行开闸
			if (Tools.isEmpty(parkwellPayBillVo.getPayType()))
			{
				parkwellPayBill.setPayType(parkwellPayBillVo.getCarNoTye());
			} else
			{
				parkwellPayBill.setPayType(parkwellPayBillVo.getPayType());
			}
			
			if (Tools.isEmpty(parkwellPayBill.getActualPrice())
					|| parkwellPayBill.getActualPrice() < 0)
			{
				parkwellPayBill.setActualPrice(0d);
			}
			
			// 如是自动扣费
			if (parkwellPayBillVo.isAuotPayOut())
			{
				Integration ingra = integrationService
						.queryInterationByCarNo(parkwellPayBillVo.getCarNo());
				ingra.setLessPrice(ingra.getLessPrice()
						- parkwellPayBillVo.getPriceDifference());
				integrationService.updateByPrimaryKeySelective(ingra);
				parkwellPayBill.setActualPrice(parkwellPayBillVo
						.getPriceDifference());
				parkwellPayBill.setPayType("自动扣费");
			}
			
			// 2015-12-10 添加进场出场信息
			parkwellPayBill.setCarOutUuid(!Tools.isEmpty(parkwellPayBillVo
					.getCarOutUuid()) ? parkwellPayBillVo.getCarOutUuid()
					: null);
			parkwellPayBill.setCaroutCareteAt(!Tools.isEmpty(parkwellPayBillVo
					.getCarOutTime()) ? parkwellPayBillVo.getCarOutTime()
					: new Date());
			parkwellPayBill.setCarinCreatAt(parkwellPayBillVo.getCarInTime());
			if (!Tools.isEmpty(parkwellPayBill.getCarinCreatAt())
					&& !Tools.isEmpty(parkwellPayBill.getCaroutCareteAt()))
			{
				// 停车时长
				String stayTimeLong = MyDateUtil.betweenTimeString(
						parkwellPayBill.getCaroutCareteAt(),
						parkwellPayBill.getCarinCreatAt());
				parkwellPayBill.setStayTimeLong(stayTimeLong);
			}
			// 2015-12-10 end
			
			localPayBillMapper.insertSelective(parkwellPayBill);
			
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
		return parkwellPayBill;
	}
	
	@Override
	public void savePayBillCopy(LocalPayBillCopy localPayBillCopy)
	{
		// TODO Auto-generated method stub
		localPayBillCopy.setPayBillUuid(UUIDGenerateUtil.generate());
		localPayBillCopy.setPayTime(new Date());
		localPayBillCopyMapper.insertSelective(localPayBillCopy);
	}
	
	@Override
	public List<LocalPayBillCopy> queryByCarInUuid(String carInUuid)
	{
		// TODO Auto-generated method stub
		List<LocalPayBillCopy> li = localPayBillCopyMapper
				.queryByCarInUuid(carInUuid);
		return !Tools.isEmpty(li) ? li : null;
	}
	
	@Override
	public LocalPayBillCopy queryLastBillCopy(String carInUuid)
	{
		// TODO Auto-generated method stub
		LocalPayBillCopy lp = localPayBillCopyMapper
				.queryLastBillCopy(carInUuid);
		return !Tools.isEmpty(lp) ? lp : null;
	}
	
	@Override
	public List<LocalPayBillCopy> queryListByCarInUuid(String carInUuid)
	{
		// TODO Auto-generated method stub
		List<LocalPayBillCopy> list = localPayBillCopyMapper
				.queryListByCarInUuid(carInUuid);
		return !Tools.isEmpty(list) ? list : null;
	}
	
	@Override
	public void saveCentralPayBill(ParkwellPayBillVo parkwellPayBillVo)
	{
		// TODO Auto-generated method stub
		LocalPayBillCopy localPayBillCopy = new LocalPayBillCopy();
		if (!Tools.isEmpty(parkwellPayBillVo))
		{
			localPayBillCopy.setPayBillUuid(UUIDGenerateUtil.generate());
			
			// 处理纸质优惠券
			if (!Tools.isEmpty(parkwellPayBillVo.getCoupon())
					&& parkwellPayBillVo.getCoupon() > 0)
			{
				LocalCoupon lcoupon = new LocalCoupon();
				lcoupon.setBillUuid(localPayBillCopy.getPayBillUuid());
				lcoupon.setCarNo(parkwellPayBillVo.getCarNo());
				lcoupon.setCouponPrice(parkwellPayBillVo.getCoupon()
						.doubleValue());
				lcoupon.setCouponUuid(UUIDGenerateUtil.generate());
				lcoupon.setPayTime(new Date(System.currentTimeMillis()));
				lcoupon.setUserId(parkwellPayBillVo.getUserUuid());
				lcoupon.setUserName(parkwellPayBillVo.getUserName());
				localCouponService.insertSelective(lcoupon);
				
				// 2015-11-20 防止线程死锁。
				parkwellPayBillVo.setLcoupon(lcoupon);
				
				// 流水实际支付减去纸质优惠券金额
				Double payNmub = parkwellPayBillVo.getPriceDifference();
				if (!Tools.isEmpty(payNmub)
						&& payNmub - parkwellPayBillVo.getCoupon() > 0)
				{
					localPayBillCopy.setActualPrice(payNmub
							- parkwellPayBillVo.getCoupon());
				}
			}
			localPayBillCopy.setCarNo(!Tools.isEmpty(parkwellPayBillVo
					.getCarNo()) ? parkwellPayBillVo.getCarNo() : "无效车牌");
			localPayBillCopy.setPayTime(new Date());
			localPayBillCopy.setPayType(!Tools.isEmpty(parkwellPayBillVo
					.getPayType()) ? parkwellPayBillVo.getPayType() : "现金");
			localPayBillCopy.setPrice(!Tools.isEmpty(parkwellPayBillVo
					.getTheoryPriceDb()) ? parkwellPayBillVo.getTheoryPriceDb()
					: 0);
			localPayBillCopy.setParkInUuid(!Tools.isEmpty(parkwellPayBillVo
					.getCarInUuid()) ? parkwellPayBillVo.getCarInUuid() : null);
			localPayBillCopy
					.setActualPrice(!Tools.isEmpty(localPayBillCopy
							.getActualPrice()) ? localPayBillCopy
							.getActualPrice()
							: !Tools.isEmpty(parkwellPayBillVo
									.getPriceDifference()) ? parkwellPayBillVo
									.getPriceDifference() : 0d);
			localPayBillCopy.setUserId(!Tools.isEmpty(parkwellPayBillVo
					.getUserUuid()) ? parkwellPayBillVo.getUserUuid() : null);
			localPayBillCopy.setUserName(!Tools.isEmpty(parkwellPayBillVo
					.getUserName()) ? parkwellPayBillVo.getUserName() : null);
			localPayBillCopy.setCarOutUuid(!Tools.isEmpty(parkwellPayBillVo
					.getCarOutUuid()) ? parkwellPayBillVo.getCarOutUuid()
					: null);
			localPayBillCopy.setCaroutCareteAt(!Tools.isEmpty(parkwellPayBillVo
					.getCarOutTime()) ? parkwellPayBillVo.getCarOutTime()
					: null);
			localPayBillCopy.setCarinCreatAt(!Tools.isEmpty(parkwellPayBillVo
					.getCarInTime()) ? parkwellPayBillVo.getCarInTime() : null);
			if (!Tools.isEmpty(localPayBillCopy.getCarinCreatAt())
					&& !Tools.isEmpty(localPayBillCopy.getCaroutCareteAt()))
			{
				// 停车时长
				String stayTimeLong = MyDateUtil.betweenTimeString(
						localPayBillCopy.getCaroutCareteAt(),
						localPayBillCopy.getCarinCreatAt());
				localPayBillCopy.setStayTimeLong(stayTimeLong);
			}
		}
		localPayBillCopyMapper.insertSelective(localPayBillCopy);
	}
	
	@Override
	public List<WorkUserPayBillVo> countUserBill(String stationUuid,
			String rotaStartTime, String rotaEndTime)
	{
		// TODO Auto-generated method stub
		List<WorkUserPayBillVo> list = localPayBillMapper.countUserBill(
				stationUuid, rotaStartTime, rotaEndTime);
		return list;
	}
	
	@Override
	public List<WorkUserPayBillVo> countUserAndTypeBill(String stationUuid,
			String rotaStartTime, String rotaEndTime)
	{
		// TODO Auto-generated method stub
		List<WorkUserPayBillVo> list = localPayBillMapper.countUserAndTypeBill(
				stationUuid, rotaStartTime, rotaEndTime);
		return list;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public Double countCarNoRepeatMoney(String carNo)
	{
		// TODO Auto-generated method stub
		/* localPayBillRepeatMapper */
		LocalPayBillRepeatExample ex = new LocalPayBillRepeatExample();
		
		// 今天最小时间
		Date lessTime = new Date();
		lessTime.setHours(0);
		lessTime.setMinutes(0);
		lessTime.setSeconds(0);
		
		// 今天最大时间s
		Date maxTime = new Date();
		maxTime.setHours(23);
		maxTime.setMinutes(59);
		maxTime.setSeconds(59);
		
		ex.or().andPayTimeBetween(lessTime, maxTime)
				.andCarNoEqualTo(carNo.trim());
		List<LocalPayBillRepeat> list = localPayBillRepeatMapper
				.selectByCondition(ex);
		
		double result = 0d;
		for (LocalPayBillRepeat billInfo : list)
		{
			if (!Tools.isEmpty(billInfo.getActualPrice()))
			{
				result += billInfo.getActualPrice();
			}
		}
		return result;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public Double countCarNoNext(String carNo)
	{
		LocalPayBillRepeatExample ex = new LocalPayBillRepeatExample();
		// 今天最小时间
		Date lessTime = new Date();
		lessTime.setHours(0);
		lessTime.setMinutes(0);
		lessTime.setSeconds(0);
		ex.or().andPayTimeLessThan(lessTime).andCarNoEqualTo(carNo.trim());
		;
		List<LocalPayBillRepeat> list = localPayBillRepeatMapper
				.selectByCondition(ex);
		
		double result = 0d;
		for (LocalPayBillRepeat billInfo : list)
		{
			if (!Tools.isEmpty(billInfo.getActualPrice()))
			{
				result += billInfo.getActualPrice();
			}
		}
		return result;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public Integer delRepaetBillNotInDay(ParkwellPayBillVo billVo)
			throws BaseException
	{
		try
		{
			LocalPayBillRepeatExample ex = new LocalPayBillRepeatExample();
			// 今天最小时间
			Date lessTime = new Date();
			lessTime.setHours(0);
			lessTime.setMinutes(0);
			lessTime.setSeconds(0);
			ex.or().andPayTimeLessThan(lessTime)
					.andCarNoEqualTo(billVo.getCarNo().trim());
			localPayBillRepeatMapper.deleteByCondition(ex); // 删除非当天
		} catch (Throwable t)
		{
			log.error(t.getMessage(), t);
			throw new BaseException(t.getMessage());
		}
		return null;
	}

	@Override
	public void removePayBillByUuid(String payBillUuid) {
		try
		{
			if(Tools.isEmpty(payBillUuid)){
				localPayBillMapper.deleteAll();
			}else{
				localPayBillMapper.deleteByPrimaryKey(payBillUuid);
			}
		} catch (Throwable t)
		{
			log.error(t.getMessage(), t);
			throw new BaseException(t.getMessage());
		}
	}
}
